<?php
namespace App\Http\Controllers\Backend;

use App\Http\Requests\ApiV2\UploadRequest;
use App\Services\Business\Models\Attach;
use App\Services\Business\Models\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Services\Business\Interfaces\AttachServiceInterface;
use App\Services\Business\Services\AttachService;
use App\Http\Requests\Company\AttachRequest;
use Illuminate\Http\JsonResponse;
class AttachController extends BaseController
{
    /**
     * @var AttachService
     */
    protected $attachService;
    public function __construct(AttachServiceInterface $attachService)
    {

        $this->attachService = $attachService;

    }
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request)
    {

        $companyId = $this->check()?$this->loginCompanyId():$request->input('company_id');
        $userIds = $request->input('user_ids');
        $my_category_id = $request->input('cid');
        $userId = $request->input('user_id');
        $keywords = $request->input('keywords', '');
        $excludeIds  = $request->input('exclude_ids',[]);
        // 排序
        $sort = $request->input('sort', 'created_at');
        $order = $request->input('order', 'desc');

        $attaches = Attach::query()
            ->with(['user'])
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($my_category_id, function ($query) use ($my_category_id) {
                $query->where('category_id', $my_category_id);
            })
            ->when($excludeIds, function ($query) use ($excludeIds) {
                $query->whereNotIn('id',$excludeIds);
            })
            ->when($userIds, function ($query) use ($userIds) {
                return $query->whereIn('id', $userIds);
            })
            ->when($userId, function ($query) use ($userId) {
                $query->where('user_id', $userId);
            })
            ->where("company_id", $companyId)
            ->orderBy($sort, $order)
            ->paginate($request->input('size', 10));
        return $this->successData(compact('attaches'));
    }

    public function upload(AttachRequest $request,Attach $attach){


        $data = $request->filldata();
        $attach->fill($data)->save();
        return $this->successData(compact('attach'));


    }


    public function replace(AttachRequest $request, $id)
    {
        $data = $request->filldata();
        $file = Attach::query()->where('id', $id)->firstOrFail();
        //删除阿里云附件
        Storage::disk('oss')->delete($file['path']);
        $file->fill($data)->save();
        return $this->success(__('附件替换成功'));

    }
    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
        public function updateTitle(Request $request, $id): JsonResponse
    {
        $title = $request->input('name');
        $attach = Attach::query()->where('id', $id)->firstOrFail();
        $attach->update(['name' => $title]);
        return $this->success(__('附件更新成功'));
    }
    /**
     * @param $id
     * @return JsonResponse
     */
    public function delete($id)
    {
        $attach = Attach::query()->where('id', $id)->firstOrFail();
        // 删除附件
        Storage::disk('oss')->delete($attach['path']);

        // 删除数据库记录
        $attach->delete();

        return $this->success();
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */

    public function batchDelete(Request $request)
    {

        $ids = $request->input('ids');
        if (!$ids) {
            return   $this->error(__('参数错误'));
        }
        $paths = Attach::whereIn('id', $ids)->select(['path'])->get()->pluck('path')->toArray();
        // 删除附件
        Storage::disk('oss')->delete($paths);

        // 删除数据库记录
        Attach::destroy($ids);

        return $this->success(__('文件删除成功'));
    }




    public function attachDownload($id)
    {
        $attach = Attach::query()->where('id',$id)->first();
        $this->downFile($attach->url, $attach->title);
    }

}
